package com.netrust.cmsx.core.service;


import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.netrust.cmsx.core.persist.BaseDao;
import com.netrust.cmsx.core.persist.BaseEntity;
import com.netrust.cmsx.utils.excute.ExcuteTime;

/**
 * Service基类
 * @param <T>
 */
@Transactional(readOnly=true)
public class CrudService<T extends BaseEntity<T>,ID extends Serializable,D extends BaseDao<T,ID>> {
	
	/**
	 * 持久层对象
	 */
	@Autowired
	protected D dao;
	

	/**
	 * 获取单条数据
	 * @param id
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public T findOne(ID id) {
		ExcuteTime c=new ExcuteTime();
		T t =dao.findOne(id);
		c.new Balance().print("dao.findOne");
		return t;
	}
	
	/**
	 * 获取全部数据
	 */
	public List<T> findAll() {
		return dao.findAll();
	}
	
	/**
	 * 分页查询数据
	 */
	public Page<T> findList(Specification<T> spec,Pageable pageable) {
		return dao.findAll(spec, pageable);
	}
	
	/**
	 * 查询分页数据
	 * @param page 分页对象
	 * @param entity
	 * @return
	 */
	public Long findPage(Specification<T> spec) {
		return dao.count(spec);
	}

	/**
	 * 保存数据（插入或更新）
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public void save(T entity) {
		if (entity.getWhetherNew()){
			entity.preInsert();
			dao.save(entity);
		}else{
			entity.preUpdate();
			dao.saveAndFlush(entity);
		}
	}
	
	/**
	 * 删除数据
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public void delete(ID id) {
		dao.delete(id);
	}
}
